﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Chinaer.WCF.WebHost
{
    public class NoSvcModule : IHttpModule
    {
        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += delegate
            {                
                HttpContext ctx = HttpContext.Current;
                string fullPath = ctx.Request.Url.AbsoluteUri;
                string apiToken = ctx.Request["apitoken"];
                if (string.IsNullOrEmpty(apiToken))
                {
                    
                }
                try
                {
                    Chinaer.Core.Helper.LogHelper.Instance.WriteLog("RequestUrls", "FormAllKeys", ctx.Request.Form.AllKeys.Count<string>() > 0 ? ctx.Request.Form[0] : "Keys为0");
                    Chinaer.Core.Helper.LogHelper.Instance.WriteLog("RequestUrls", "requestUrl", fullPath);
                    Chinaer.Core.Helper.LogHelper.Instance.WriteLog("RequestUrls", "Method", ctx.Request.HttpMethod);
                }
                catch (Exception ex)
                {
                    Chinaer.Core.Helper.LogHelper.Instance.WriteLog("RequestUrls", "Exception", ex.Message);
                }
                Chinaer.Core.Helper.LogHelper.Instance.WriteLog("RequestUrls", "PathInfo", ctx.Request.PathInfo);
                //获取当前请求的相对路径
                string path = ctx.Request.AppRelativeCurrentExecutionFilePath;
                Chinaer.Core.Helper.LogHelper.Instance.WriteLog("RequestUrls", "AppRelativeCurrentExecutionFilePath", path);
                int i = path.IndexOf("/", 2);//~/login.svc
                if (i > 0)
                {
                    string svc = path.Substring(0, i) + ".svc";
                    string rest = path.Substring(i, path.Length - i);
                    string qs = ctx.Request.QueryString.ToString();
                    ctx.RewritePath(svc, rest, qs, false);
                }
            };
            context.Error += delegate
            {
                context.Error += delegate
                {
                    Exception ex = context.Server.GetLastError();
                    Chinaer.Core.Helper.LogHelper.Instance.WriteLog("ModuleError", "Module", ex.Message);
                };

            };
        }

    }
}